
class Autofit {
  /**
   *
   * @param {*} options 配置项
   *                       draftWidth 设计图宽度
   *                       draftHeight 设计图高度
   *                       dom 元素选择器
   *                       fullDocument 是否铺满视图显示
   *                       transition 过度效果时间
   * @param {*} isShowInitTip 是否打印初始化提示
   */
  constructor(options, isShowInitTip = true) {
    this.draftWidth = options.designWidth || 1920
    this.draftHeight = options.designHeight || 929
    this.dom = document.querySelector(options.renderDom)
    this.isShowInitTip = isShowInitTip
    this.delay = options.delay || 500
    this.fullDocument = options.fullDocument || true // 是否铺满视图显示， 如果不是铺满视图显示必须设为false，否则会影响元素大小
    this.transition = options.transition || 0.4
  }
  init() {
    if (this.isShowInitTip) {
      console.log(`%c` + `autofit.js` + ` is running`, `font-weight: bold; color: #ffb712; background:linear-gradient(-45deg, #bd34fe 50%, #47caff 50% );background: -webkit-linear-gradient( 120deg, #bd34fe 30%, #41d1ff );background-clip: text;-webkit-background-clip: text; -webkit-text-fill-color:linear-gradient( -45deg, #bd34fe 50%, #47caff 50% ); padding: 8px 12px; border-radius: 4px;`)
    }
    if (!this.dom) {
      console.error('没有找到该元素')
      return
    }
    this.dom.style.transformOrigin = '0 0'
    this.dom.style.transition = this.transition + 's'
    const style = document.createElement('style')
    style.lang = 'text/css'
    style.id = 'autofit-style'
    style.innerHTML = `
      body {
        overflow: hidden;
      }
    `
    let timer
    this.dom.appendChild(style)
    const resizeListener = () => {
      clearTimeout(timer)
      timer = setTimeout(() => {
        keepfit(this.draftWidth, this.draftHeight, this.dom)
        clearTimeout(timer)
      }, this.delay)
    }
    keepfit(this.draftWidth, this.draftHeight, this.dom, this.fullDocument)
    window.onresize = resizeListener
  }
  off() {
    window.removeEventListener('resize', this.resizeListener)
    document.querySelector('#autofit-style').remove()
    this.dom && (this.dom.style = '')
    this.isShowInitTip && console.log(`%c` + `autofit.js` + ` is off`, `font-weight: bold;color: #707070; background: #c9c9c9; padding: 8px 12px; border-radius: 4px;`)
  }
}
function keepfit(draftWidth, draftHeight, dom, fullDocument) {
  let clientHeight = document.documentElement.clientHeight
  let clientWidth = document.documentElement.clientWidth
  if (!fullDocument) {
    // 获取到元素距离视图的距离，场景为不是全屏显示的情况下
    const { left, top } = dom.getBoundingClientRect()
    clientHeight -= top
    clientWidth -= left
  }
  let scale = 1
  scale = (clientWidth / clientHeight) < (draftWidth / draftHeight) ? clientWidth / draftWidth : clientHeight / draftHeight
  dom.style.width = clientWidth / scale + 'px'
  dom.style.height = clientHeight / scale + 'px'
  dom.style.transform = `scale(${scale})`
}
export default Autofit
